package commonutils;

import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.xpath.XPathUtils;

import java.util.List;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Evgeniy Krasko
 * Date: 30.10.11
 * Time: 18:31
 */
public class MyXPathUtils {
    public static final Logger logger = Logger.getLogger(MyXPathUtils.class.getName());

    private MyXPathUtils() {
    }

    public static DomNode getSingleDomNode(DomNode node, String xPathExpr) {
        List<Object> list = XPathUtils.getByXPath(node, xPathExpr);
        if (list.isEmpty()) {
            logger.fine("Not found by xpath " + xPathExpr + " in " + node.getNodeName());
            return null;
        }
        DomNode result = null;
        if (list.get(0) instanceof DomNode) {
            result = (DomNode) list.get(0);
        }
        if (list.size() > 1) {
            logger.warning(node.getNodeName() + " contains more than one element by xpath " + xPathExpr);
        }
        if (result == null) {
            logger.warning(list.get(0) + " is not DomNode!");
        }
        return result;
    }
}
